const wx = require('./common');
const db = uniCloud.database()
// 获取二维码 暂时用不到
async function getQrcode(data) {
	// 获取参数
	if (!data) {
		return {
			code: 400,
			data: "ticket不能为空"
		}
	}
	let Url =
		`https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${data}`
	let result = await uniCloud.httpclient.request(Url, {
		method: 'POST',
		data: {},
		dataType: 'json'
	})
	// 添加到后台服务器
	return result

}
// 创建二维码ticket
async function getTicket(data) {
	// 获取参数
	let access_token = await wx.getToken()
	let Url =
		`https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=${access_token}`
	let result = await uniCloud.httpclient.request(Url, {
		method: 'POST',
		data: JSON.stringify(data),
		dataType: 'json'
	})
	// 添加到后台服务器
	// 将数据存到后台服务器
	let serviceRes = await db.collection('qrcode').where({
		ticket: result.data.ticket,
		action_name: data.action_name
	}).count()
	if (serviceRes.total > 0) {
		return {
			code: 400,
			data: '二维码已存在'
		}
	}
	let adddata = { ...result.data,
		...data
	}
	await db.collection('qrcode').add(adddata)
	return result
}

// 获取素材列表
async function getList(data) {
	let count = data.count || 20
	let offset = data.offset || 0
	let res = await db.collection('qrcode').limit(count).skip(count * offset).get()
	return res
}
// 获取素材列表
async function del(data) {
	if (!data.id) {
		return {
			code: 400,
			data: '非法id'
		}
	}
	let res =await db.collection('qrcode').doc(data.id).remove()
	return res
}


module.exports = {
	getTicket,
	getList,
	getQrcode,
	del

}
